package com.dove.ohpm.ui

import com.dove.ohpm.service.NetClient
import com.dove.ohpm.service.UISettingConfigState
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.options.Configurable
import javax.swing.JComponent

class UISettingConfig: Configurable {
    private val form = setting()
    private val component: JComponent = form.mainPanel
    private val state = ApplicationManager.getApplication().getService(UISettingConfigState::class.java)

    override fun createComponent() = component

    override fun isModified() = true

    init {
        form.txtHost.text = state.hostUrl
        form.txtPort.text = state.hostPort.toString()
        form.cbSchema.selectedIndex = if (state.hostSchema == "http") 0 else 1
    }

    override fun apply() {
        val hostUrl = form.txtHost.text
        var hostPort = form.txtPort.text.toIntOrNull()
        if (hostPort == null)
            hostPort = 0
        val schema = if (form.cbSchema.selectedItem == null) "http" else form.cbSchema.selectedItem!!.toString()
        state.hostUrl = hostUrl
        state.hostSchema = schema
        state.hostPort = hostPort
        NetClient.setCustomHostUrl(schema, hostUrl, hostPort)
    }

    override fun reset() {
        state.hostUrl = ""
        state.hostPort = 0
        state.hostSchema = "http"
        NetClient.setCustomHostUrl("http", "", 0)
        super.reset()
    }

    override fun getDisplayName() = "UISettingConfig"
}